package com.suneee.store.dao.impl;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.suneee.orm.GenericDao;
import com.suneee.orm.util.WhereClauseBuilder;
import com.suneee.store.dao.SkuDao;
import com.suneee.store.entity.Sku;

@Repository("skuDao")
public class SkuDaoImpl extends GenericDao<Sku, Integer> implements SkuDao {

	@Override
	public List<Sku> queryForListBySpu(List<Integer> spuIdList) {
		// TODO Auto-generated method stub
		if(spuIdList == null || spuIdList.isEmpty())
			return null;
		String sql = " spu_id in (";
		for(int i = 0;i < spuIdList.size();i++){
			if(i == spuIdList.size() - 1){
				sql += spuIdList.get(i);
			}
			else{
				sql += spuIdList.get(i) + ",";
			}
		}
		sql += ")";
		Object[] objs = null;
		return this.selectWhere(sql, objs);
	}

	@Override
	public void updateStock(Integer skuId, Integer sub) {
		// TODO Auto-generated method stub
		Sku sku = this.select(skuId);
		sku.setStock(sku.getStock() - sub);
		sku.setAssignedStock(sku.getAssignedStock() + sub);
		this.update(sku);
	}

	@Override
	public List<Sku> queryForListBySpuId(Integer spuId) {
		// TODO Auto-generated method stub
		String sql = " spu_id = ?";
		return this.selectWhere(sql, spuId);
	}

	@Override
	public List<Sku> getListBySpuIdAndSpecValue(Integer spuId, String specValue) {
		// TODO Auto-generated method stub
		String sql = " spu_id = ? "
				+ "and (spec_one_value = ? or spec_two_value = ? or spec_three_value = ? or spec_four_value = ?)";
		Object[] args = {spuId,specValue,specValue,specValue,specValue};
		return this.selectWhere(sql, args);
	}

	@Override
	public Integer getMaxSkuIdBySpuId(Integer spuId) {
		// TODO Auto-generated method stub
		String sql = "select max(sku_id) as sku_id from t_sku where concat(sku_id) like ? ";
		String args = String.valueOf(spuId) + "%";
		List<Map<String,Object>> list = this.queryForList(sql, args);
		if(list == null || list.isEmpty())
			return null;
		return (Integer) list.get(0).get("sku_id");
	}

	@Override
	public Sku getSameSku(Sku sku) {
		// TODO Auto-generated method stub
		WhereClauseBuilder builder = new WhereClauseBuilder();
	    builder.equals("spu_id", sku.getSpuId());
	    builder.equals("spec_one_value", sku.getSpecOneValue());
	    builder.equals("spec_two_value", sku.getSpecTwoValue());
	    builder.equals("spec_three_value", sku.getSpecThreeValue());
	    builder.equals("spec_four_value", sku.getSpecFourValue());
	    List<Sku> list = this.selectWhere(builder.getSql(), builder.getArgs());
	    if(list == null || list.isEmpty())
	    	return null;
	    return list.get(0);
	}
	
}
